//
//  ByCoreToolUrlSchemeHandler.m
//  itboye2015002
//
//  Created by hebidu on 15/9/20.
//  Copyright © 2015年 Boye. All rights reserved.
//
#import "ByCoreToolUrlSchemeHandler.h"

@interface ByCoreToolUrlSchemeHandler()



@end



// 控制器
@implementation ByCoreToolUrlSchemeHandler


static NSMutableDictionary * handlers;

+ (void) registerScheme:(NSString *) scheme :(id ) obj{
    
    
    if(handlers == nil){
        handlers = [[NSMutableDictionary alloc] init];
    }
    
    NSMutableArray * value = [handlers objectForKey:scheme];
    if(value == nil){
        value = [[NSMutableArray alloc]init];
    }
    
    if(obj != nil){
        [value addObject:obj];
    }
    
    [handlers setObject:value forKey:scheme];
    
}


+ (BOOL)handleOpenURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options{
    if(handlers == nil){
        return NO;
    }
    // 判断是否本app 处理
    NSArray * allKeys = [handlers allKeys];
    
    NSString *query = [url query];
    
    // 获得了参数字典
    NSDictionary *params = [self parseURLParams:query];

    
    for (NSString  * key in allKeys) {
        
        if ([[url scheme] isEqualToString:key]) {
            
            NSMutableArray * value = [handlers objectForKey:key];
            
            for (id controller in value) {
                
                #pragma clang diagnostic push
                #pragma clang diagnostic ignored"-Wundeclared-selector"
                
                if([controller respondsToSelector:@selector(handle: params:)]){
                    [controller performSelector:@selector(handle: params:) withObject:url withObject:params];
                }
                
                #pragma clang diagnostic pop
            }
            
            return YES;
            
        }

    }
    return NO;
}

// 分解参数
+ (NSDictionary *)parseURLParams:(NSString *)query{
    
    NSArray *paramsAry = [query componentsSeparatedByString:@"&"];
    NSMutableDictionary *paramsDic = [[NSMutableDictionary alloc] init];
    for (NSString *params_keyValue in paramsAry) {
        NSArray *keyValue = [params_keyValue componentsSeparatedByString:@"="];
        if (keyValue.count == 2) {
            
            // %E8%AE%A2%E5%8D -> 订单     对这样的字符串进行解码
            NSString *value = [[keyValue lastObject] stringByRemovingPercentEncoding];
            
            [paramsDic setObject:value forKey:[keyValue firstObject]];
        }
    }
    return [paramsDic copy];
}


@end
